package org.darkhelm.showsort.server.servlet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

@SuppressWarnings("serial")
public class JythonSerializationTestServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
		ScriptEngine engine = new ScriptEngineManager()
				.getEngineByName("python");

		resp.setContentType("text/plain");
		
		PrintWriter out = null;
		ScriptEngine engine2;

		byte[] engineSer = null;

		try {
			out = resp.getWriter();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			engine.put("x", "5");
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			ObjectOutputStream oos = new ObjectOutputStream(baos);

			oos.writeObject(engine);
			oos.close();

			engineSer = baos.toByteArray();

			ObjectInputStream ois = new ObjectInputStream(
					new ByteArrayInputStream(engineSer));

			engine2 = (ScriptEngine) ois.readObject();
			ois.close();
			
			out.println(engine2.get("x"));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace(out);
		}
		

		/*
		 * // Using the eval() method on the engine causes a direct //
		 * interpretataion and execution of the code string passed into it
		 * engine.eval("import sys"); engine.eval("print sys");
		 * 
		 * // Using the put() method allows one to place values into //
		 * specified variables within the engine engine.put("a", "42");
		 * 
		 * // As you can see, once the variable has been set with // a value by
		 * using the put() method, we an issue eval statements // to use it.
		 * engine.eval("print a"); engine.eval("x = 2 + 2");
		 * 
		 * // Using the get() method allows one to obtain the value // of a
		 * specified variable from the engine instance Object x =
		 * engine.get("x"); System.out.println("x: " + x);
		 */
	}
}
